import random
import arrow
from app.errors import Success
from app.validators.active import SmsCaptchaForm
from flask import session, jsonify, current_app as app
from flask.helpers import make_response
from app.libs.redprint import RedPrint
from app.libs.captcha import Captcha
from app.libs.yunpian import YunPian

api = RedPrint('captcha')


@api.route('/image', methods=['GET'])
def image():
    captcha = Captcha(rate=0.95, img_width=105)
    captcha.display()
    # 设置session
    session[captcha.key] = captcha.answer
    session[captcha.expire_key] = arrow.utcnow().for_json()

    response = make_response(captcha.captcha)
    response.headers['Content-Type'] = 'image/gif'
    return response


@api.route('/sms', methods=['POST'])
def sms():
    form = SmsCaptchaForm().validate_for_api()
    # 生成sms code
    sms_code = "%06d" % random.randint(0, 999999)
    app.logger.debug(f'sms code: {sms_code}, phone: {form.contactsPhone.data}')
    yunpian = YunPian()
    args = f'#code#={sms_code}'
    yunpian.tpl_send(form.contactsPhone.data, 5238810, args)
    # 设置session
    session['smsCode'] = sms_code
    session['contactsPhone'] = form.contactsPhone.data
    session['lastSmsTime'] = arrow.utcnow().for_json()
    return Success()
